package com.app.public_dependency.generator;

import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.ScreenshotType;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author zhangzy
 * @description 报告输出生成器
 */
@Slf4j
public class ReportGenerator {

    private static final String SCREENSHOT_DIR = "c:\\pw\\pwtest\\temp\\screenshots";

    private static final String REPORT_DIR_STRING = "C:\\pw\\pwtest\\report";

    /**
     * 屏幕截图
     *
     * @param page           PAGE
     * @param screenshotName 文件名
     */
    public String captureScreenshot(Page page, String screenshotName) {

        Page.ScreenshotOptions options = new Page.ScreenshotOptions();
        options.setType(ScreenshotType.PNG);
        options.setFullPage(true);
        byte[] screenshot = page.screenshot(options);
        screenshotName = screenshotName + ".png";
        String screenshotPath = SCREENSHOT_DIR + File.separator + LocalDate.now() + File.separator
                + screenshotName;

        File photoPath = Path.of(SCREENSHOT_DIR + File.separator + LocalDate.now()).toFile();
        if (!photoPath.exists()) {
            photoPath.mkdirs();
        }
        try {
            Files.createDirectories(Path.of(SCREENSHOT_DIR));
            Files.write(Path.of(screenshotPath), screenshot);
            return screenshotPath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 报告生成
     *
     * @param imagePaths 文件解析列表
     * @param fileName   报告名称
     */
    public void createReport(String fileName, List<String> imagePaths) {

        if (fileName == null) {
            return;
        }
        List<String> infoList = new ArrayList<>();
        if (imagePaths == null) {
            List<String> pathList = new ArrayList<>();
            Path startPath = Paths.get(SCREENSHOT_DIR, LocalDate.now().toString());
            try {
                Files.walkFileTree(startPath, new SimpleFileVisitor<>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (file.getFileName().toString().startsWith(fileName)) {
                            pathList.add(file.toString());
                            if (file.toString().endsWith(".txt")) {
                                infoList.add(file.toString());
                            }
                        }
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFileFailed(Path file, IOException exc) {
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
            imagePaths = new ArrayList<String>(pathList);
        }

        if (infoList.size() == 0) {
            return;
        }

        HashMap<String, String> urlMap = getUrlMap(infoList.get(0));

        // workbook作成
        Workbook workbook = new XSSFWorkbook();
        // sheet作成
        Sheet sheet = workbook.createSheet("エビデンス");
        try {
            int rowCount = 1;
            CreationHelper helper = workbook.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();
            // 追加
            for (int i = 0; i < imagePaths.size(); i++) {
                if (imagePaths.get(i).endsWith(".txt")) {
                    continue;
                }
                byte[] imageBytes;

                imageBytes = Files.readAllBytes(Paths.get(imagePaths.get(i)));
                int pictureIndex = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
                ClientAnchor anchor = helper.createClientAnchor();
                anchor.setCol1(1);
                anchor.setRow1(rowCount + 2 * i);
                Picture picture = drawing.createPicture(anchor, pictureIndex);
                picture.resize();

                Row row = sheet.createRow(rowCount + 2 * i - 1);
                Cell cell = row.createCell(1);
                cell.setCellValue(urlMap.get(Path.of(imagePaths.get(i)).getFileName().toString()));

                ClientAnchor anchor1 = picture.getPreferredSize();
                rowCount = rowCount + anchor1.getRow2() - anchor1.getRow1();
            }

            File fileDir = new File(REPORT_DIR_STRING);
            if (!fileDir.exists()) {
                if (!fileDir.mkdirs()) {
                    workbook.close();
                    return;
                }
            }
            Files.deleteIfExists(Path.of(REPORT_DIR_STRING, fileName + "_エビデンス.xlsx"));

            // 文件生成
            FileOutputStream fos = new FileOutputStream(
                    new File(Path.of(REPORT_DIR_STRING, fileName + "_エビデンス.xlsx").toString()));
            workbook.write(fos);
            fos.close();
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                for (String p : imagePaths) {
                    Files.delete(Path.of(p));
                }

                Files.deleteIfExists(Path.of(SCREENSHOT_DIR, LocalDate.now().toString()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public String createInfo(String infoName) {
        try {
            File photoPath = Path.of(SCREENSHOT_DIR + File.separator + LocalDate.now()).toFile();
            if (!photoPath.exists()) {
                if (photoPath.mkdirs()) {
                    log.info("文件夹创建成功");
                } else {
                    log.error("文件夹创建失败");
                }
            }

            File file = new File(
                    SCREENSHOT_DIR + File.separator + LocalDate.now() + File.separator + infoName + ".txt");
            if (file.createNewFile()) {
                return file.getPath();
            } else {
                return null;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void writeInfo(String filePath, List<String> lines) {
        Path path = Paths.get(filePath);
        try {
            Files.write(path, lines, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HashMap<String, String> getUrlMap(String infoFile) {
        HashMap<String, String> dataHashMap = new HashMap<String, String>();

        Path filePath = Paths.get(infoFile);
        try {
            List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
            for (int i = 0; i < lines.size(); i++) {
                dataHashMap.put(lines.get(i), lines.get(i + 1));
                i = i + 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataHashMap;

    }

}
